import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_model/video_model.dart';
import 'package:xvideos/hj_utils/api_service/mine_service.dart';
import 'package:xvideos/hj_utils/format_util.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:xvideos/routers/jump_router.dart';
import 'package:xvideos/tools_base/global_store/store.dart';
import 'package:xvideos/tools_base/loading/LoadingHelper.dart';
import 'package:xvideos/tools_base/net/base_resp_bean.dart';

class VideoBuyBottomSheet extends StatefulWidget {
  final VideoModel videoM;
  final bool presale;
  const VideoBuyBottomSheet({super.key, required this.videoM, this.presale = false});

  @override
  State<VideoBuyBottomSheet> createState() => _VideoBuyBottomSheetState();
}

class _VideoBuyBottomSheetState extends State<VideoBuyBottomSheet> {
  @override
  void initState() {
    super.initState();
    globalStore.updateUserInfo();
    globalStore.refreshWallet();
  }

  bool get isCartoon => widget.videoM.videoType == 1;

  //图集和黄游金币解锁，没有vip折扣
  bool get hasNoDiscount => (widget.videoM.newsType == "PIC" || widget.videoM.newsType == "SEED_LINK");

  bool get isSeedLink => widget.videoM.newsType == 'SEED_LINK';

  @override
  Widget build(BuildContext context) {
    return Consumer<GlobalStore>(
      builder: (_, store, __) {
        final enough = (store.wallet?.amount ?? 0) >= (widget.videoM.realCoins ?? 0);
        return _buildNormal(enough, store);
      },
    );
  }

  Widget _buildNormal(bool enough, GlobalStore store) {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(horizontal: 16, vertical: 18),
      decoration: BoxDecoration(
        color: Color(0xff030F18),
        borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            width: 36,
            height: 5,
            child: DecoratedBox(
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(.2),
                borderRadius: BorderRadius.circular(3),
              ),
            ),
          ),
          18.sizeBoxH,
          Text(
            '购买作品',
            style: TextStyle(
              color: Color(0xE5ffffff),
              fontSize: 20,
              fontWeight: FontWeight.w500,
            ),
          ),
          36.sizeBoxH,
          Row(
            children: [
              Text(
                '作品解锁',
                style: TextStyle(
                  color: Color(0xE5ffffff),
                  fontSize: 14,
                ),
              ),
              Spacer(),
              GestureDetector(
                onTap: () => jumpToWalletPage(tabPosition: 1),
                child: Row(
                  children: [
                    Image.asset(
                      'coin_x.webp'.commonImgPath,
                      width: 24,
                      height: 24,
                    ),
                    10.sizeBoxW,
                    Text(
                      hasNoDiscount ? '${widget.videoM.originCoins ?? 0} 金币' : '${widget.videoM.coins ?? 0} 金币',
                      style: TextStyle(
                        color: Color(0xffFF9000),
                        fontSize: 14,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ],
                ),
              )
            ],
          ),
          18.sizeBoxH,
          if (hasNoDiscount) //图集和黄游金币解锁，没有vip折扣
            SizedBox()
          else ...[
            Row(
              children: [
                Text(
                  '作品原价',
                  style: TextStyle(
                    color: Color(0xE5FFFFFF),
                    fontSize: 14,
                  ),
                ),
                Spacer(),
                Text(
                  '${widget.videoM.originCoins ?? 0} 金币',
                  style: TextStyle(
                    color: Color(0x8CFFFFFF),
                    fontSize: 14,
                    decoration: (store.meInfo == null || store.meInfo?.vipLevel == 0) ? null : TextDecoration.lineThrough,
                    decorationColor: Color(0x8CFFFFFF),
                  ),
                ),
              ],
            ),
            18.sizeBoxH,
            Row(
              children: [
                Text(
                  () {
                    if (store.meInfo == null || store.meInfo?.vipLevel == 0) return '您当前不享受免费观看';
                    if ((widget.videoM.coins ?? 0) < (widget.videoM.originCoins ?? 0) && GlobalStore().isVIP())
                      return '您当前享受${GlobalStore().getMe()?.payVidDiscount}折优惠';

                    return '您当前不享受免费观看';
                  }(),
                  style: TextStyle(color: Color(0xffA4634D), fontSize: 14, fontWeight: FontWeight.w400),
                ),
                Spacer(),
                GestureDetector(
                  onTap: () => jumpToWalletPage(),
                  child: Text(
                    () {
                      if (store.meInfo == null || store.meInfo?.vipLevel == 0) return '购买VIP享免费观看';
                      // final discount = ((widget.videoM.coins ?? 0) / (widget.videoM.originCoins ?? 0) * 10).toInt();
                      return '升级会员';
                    }(),
                    style: TextStyle(
                      color: Color(0xffA4634D),
                      fontSize: 14,
                      fontWeight: FontWeight.w400,
                      decoration: TextDecoration.underline,
                      decorationColor: Color(0xffA4634D),
                    ),
                  ),
                ),
              ],
            ),
            18.sizeBoxH,
          ],
          Divider(
            height: 0.5,
            color: Colors.white.withOpacity(.05),
          ),
          18.sizeBoxH,
          Row(
            children: [
              Text(
                '我的金币',
                style: TextStyle(
                  color: Color(0xE5ffffff),
                  fontSize: 14,
                ),
              ),
              Spacer(),
              Row(
                children: [
                  Text(
                    '${GlobalStore().wallet?.amount?.toDouble().fixed(2) ?? 0}',
                    style: TextStyle(
                      color: Color(0xE5ffffff),
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  12.sizeBoxW,
                  InkWell(
                    onTap: () => jumpToWalletPage(tabPosition: 1),
                    child: Text(
                      '充值',
                      style: TextStyle(
                          color: Color(0xffA4634D),
                          fontSize: 14,
                          fontWeight: FontWeight.w400,
                          decoration: TextDecoration.underline,
                          decorationColor: Color(0xffA4634D)),
                    ),
                  ),
                ],
              ),
            ],
          ),
          18.sizeBoxH,
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () => _doPayAction(enough),
            child: Container(
              width: double.infinity,
              height: 47,
              decoration: BoxDecoration(color: Color(0xffE1351F), borderRadius: BorderRadius.circular(3)),
              alignment: Alignment.center,
              child: Text(
                enough ? '${hasNoDiscount ? '${widget.videoM.originCoins ?? 0} 金币' : '${widget.videoM.coins ?? 0} 金币'}/立即支付' : '余额不足，前往充值',
                style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _doPayAction(bool enough) async {
    if (!enough) {
      //showToast('余额不足');
      await jumpToWalletPage(tabPosition: 1);
    } else {
      LoadingHelper.showLoading();
      int type = 1;
      if (isSeedLink) {
        type = 1;
      } else if (isCartoon) {
        type = 19;
      } else {
        type = 1;
      }
      BaseRespBean data = await MineService.postBuyVideo(
        widget.videoM.id,
        type,
        goldVideoCouponNum: 0,
      );
      LoadingHelper.dismissLoading();
      if (data.isSuccess) {
        widget.videoM.vidStatus?.hasPaid = true;
        Get.back(result: true);
      } else {
        if (data.code == 8000) {
          jumpToWalletPage(tabPosition: 1);
        } else {
          showToast("网络异常, 支付失败");
        }
      }
    }
  }
}
